package com.song.wniter.boot;

import com.song.winter.context.AnnotationConfigApplicationContext;
import com.song.winter.context.ApplicationContext;
import com.song.winter.io.PropertyResolver;
import com.song.winter.web.WebMvcConfiguration;
import com.song.winter.web.utils.WebUtils;
import jakarta.servlet.ServletContainerInitializer;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

public class ContextLoaderInitializer  implements ServletContainerInitializer {
    final Logger logger = LoggerFactory.getLogger(getClass());
    final Class<?> configClass;
    final PropertyResolver propertyResolver;

    public ContextLoaderInitializer(Class<?> configClass, PropertyResolver propertyResolver) {
        this.configClass = configClass;
        this.propertyResolver = propertyResolver;

    }


    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        logger.info("Servlet container start. ServletContext = {}", servletContext);
        String encoding = propertyResolver.getProperty("${winter.web.character-encoding:UTF-8}");
        servletContext.setRequestCharacterEncoding(encoding);
        servletContext.setResponseCharacterEncoding(encoding);
        WebMvcConfiguration.setServletContext(servletContext);

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(this.configClass, this.propertyResolver);
        logger.info("Application context created: {}", applicationContext);
        // register filters:
        WebUtils.registerFilters(servletContext);
        // register DispatcherServlet:
        WebUtils.registerDispatcherServlet(servletContext, this.propertyResolver);


    }
}
